﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using Charities.ModelViews;


namespace Charities
{
    public partial class CartsEditor : Form
    {
        int userId = -1;
        Form fo;
        public bool is_loaded = false;
        public CartsEditor(int id,Form m)
        {
            fo = m;
            this.MdiParent = m;
            userId = id;
            InitializeComponent();
        }
        ModelContainer ctx = new ModelContainer();
        
        private void CartsEditor_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userId);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name)
                {
                    case "CARTS_ADD_CART":
                        btn_C_Add.Visible = true;
                        break;
                    case "CARTS_ADD_SUPPLY":
                        btnAdd.Visible = true;
                        txbAmmount.Visible = true;
                        cboSupply.Visible = true;
                        label3.Visible = true;
                        label4.Visible = true;
                        label5.Visible = true;
                        break;
                    case "CARTS_DELETE_CART":
                        btn_delete.Visible = true;
                        break;
                    case "CARTS_SUPPLY_DELETE":
                        btn_S_Delete.Visible = true;
                        break;
                    case "CARTS_EDIT_CART_NAME":
                        btn_edit.Visible = true;
                        break;
                    case "CARTS_EDIT_SUPPLY_NAME":
                        btnEdit.Visible = true;
                        break;
                    default:
                        break;
                }
            }

            try
            {
                cartBindingSource.DataSource = ctx.Carts.ToList();
                lstboxCarts.DataSource = cartBindingSource;
                int cid= (int)lstboxCarts.SelectedValue;
                cartDetailViewBindingSource.DataSource = GetCartdetails(cid);
                CartsDetailsdataGridView.DataSource = cartDetailViewBindingSource;
                cboSupply.DataSource = ctx.Supplies.ToList();
                cboSupply.DisplayMember = "Name";
                cboSupply.ValueMember = "Id";

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
           
        }
        private List<CartDetailView> GetCartdetails(int id)
        {
            Cart cart = ctx.Carts.Single(c => c.Id == id);
            supplyBindingSource.DataSource = ctx.Supplies.ToList();
            List<CartDetailView> cdvl = new List<CartDetailView>();
            foreach (var item in cart.CartDetails.ToList())
            {
                CartDetailView cdv = new CartDetailView();
                cdv.Ammount = item.Amount;
                cdv.supply = item.Supply.Name;
                cdv.Id = item.Id;
                cdvl.Add(cdv);
            }
            return cdvl;
        }

        private void CartsDetailsdataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            string errorStatus = String.Empty;
            DialogResult res = MessageBox.Show("هل أنت متأكد من حذف السلة؟", "تأكيد الحذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.Yes)
            {
                int? id = (int?)lstboxCarts.SelectedValue;
                if (id != null && id > 0)
                {
                    Cart cart = ctx.Carts.Single(c => c.Id == id);
                    if (cart.CartDetails.Count() == 0)
                    {
                        ctx.Carts.Remove(cart);
                    }
                    else
                    {
                        errorStatus = "- " + cart.Name + " \n ";
                    }

                }
                if (errorStatus.Length == 0)
                {
                    ctx.SaveChanges();
                    txb_AddCart.Text = String.Empty;
                    cartBindingSource.DataSource = ctx.Carts.ToList();
                    lstboxCarts.DataSource = cartBindingSource;
                    btn_delete.Enabled = false;
                }
                else
                {
                    MessageBox.Show("لايمكن حذف السلة التالية لكونها تحتوي على تفاصيل: \n " + errorStatus);
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if(lstboxCarts.SelectedValue!=null)
            {
            int cid= (int)lstboxCarts.SelectedValue;
            SupplyAdd s = new SupplyAdd(prediCartId, preCartDetailId, fo, this);
            s.FormUpdated += new SupplyAdd.UpdateFormHandler(btn_insert_Click);
            s.Show();
            }
        }

        private void btn_S_Delete_Click(object sender, EventArgs e)
        {
            string errorStatus = String.Empty;
            for (int i = 0; i < CartsDetailsdataGridView.SelectedRows.Count; i++)
            {
                try
                {
                    if (lstboxCarts.SelectedValue != null)
                    {
                        int cartId = (int)lstboxCarts.SelectedValue;
                        int id = (int)CartsDetailsdataGridView.SelectedRows[i].Cells[0].Value;
                        if (id > 0 && cartId>0)
                        {
                            CartDetail crtdet = ctx.CartDetails.Single(c => c.Id == id);

                            foreach (var grant in ctx.Grants.ToList())
                            {
                                if (grant.CartId != null)
                                {
                                    foreach (var cd in ctx.Carts.Single(c => c.Id == grant.CartId).CartDetails.ToList())
                                    {
                                        if (cd.Id == crtdet.Id && grant.InsertDate > crtdet.InsertDate && grant.IsDelivered==true)
                                        {
                                            errorStatus = cd.Supply.Name;
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (var grdet in ctx.GrantDetails.Where(c => c.SupplyId == id).ToList())
                                    {
                                        if (grdet.Id == crtdet.Id && grdet.InsertDate>crtdet.InsertDate && grdet.Grant.IsDelivered==true)
                                        {
                                            errorStatus = grdet.Supply.Name;
                                        }
                                    }
                                }
                            }
                            if (errorStatus.Length == 0)
                            {
                                ctx.CartDetails.Remove(crtdet);
                                ctx.SaveChanges();
                                if (lstboxCarts.SelectedValue != null)
                                {
                                    int cid = (int)lstboxCarts.SelectedValue;
                                    cartDetailViewBindingSource.DataSource = null;
                                    cartDetailViewBindingSource.DataSource = GetCartdetails(cid);
                                    CartsDetailsdataGridView.DataSource = cartDetailViewBindingSource;
                                }
                            }
                            else
                            {
                                MessageBox.Show("لايمكن حذف " + errorStatus + " لكونه موجود ضمن المنح");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btn_C_Add_Click(object sender, EventArgs e)
        {
            try
            {
                Cart tmp = ctx.Carts.Single(c => c.Name == txb_AddCart.Text.Trim());
                MessageBox.Show("السلة موجودة مسبقاً");
            }
            catch 
            {
                if (txb_AddCart.Text.Length > 0)
                {
                    Cart cart = new Cart();
                    cart.Name = txb_AddCart.Text.Trim();
                    cart.InsertDate = DateTime.Now;
                    cart.InsertUId = userId;
                    ctx.Carts.Add(cart);
                    ctx.SaveChanges();
                    txb_AddCart.Text = String.Empty;
                }
            }
            cartBindingSource.DataSource = (from c in ctx.Carts select c).ToList();
            lstboxCarts.DataSource = cartBindingSource;
                
        }
        string preditName;
        int prediCartId=1;
        private void CartsdataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string name = lstboxCarts.SelectedItem.ToString();
                Cart cart = ctx.Carts.Single(c => c.Name == name);
                prediCartId = cart.Id;
                txb_AddCart.Text = name;
                btn_C_Add.Enabled= false;
                btn_edit.Enabled = true;
                btn_delete.Enabled = true;
                preditName = name;
                txb_AddCart.Focus();
            }
            catch (Exception)
            {
                
                
            }
          

        }

        private void btn_edit_Click(object sender, EventArgs e)
        {
            if (txb_AddCart.Text != null && txb_AddCart.Text.Length > 0)
            {
                int id = (int)lstboxCarts.SelectedValue;
                if (id > 0)
                {
                    Cart cart = ctx.Carts.Single(c => c.Id == id);
                    cart.Name = txb_AddCart.Text;
                    cart.UpdateDate = DateTime.Now;
                    cart.UpdateUId = userId;
                    ctx.SaveChanges();
                    txb_AddCart.Text = String.Empty;
                    cartBindingSource.DataSource = ctx.Carts.ToList();
                    lstboxCarts.DataSource = cartBindingSource;
                }
            }
        }

        private void txb_AddCart_Click(object sender, EventArgs e)
        {
            if (txb_AddCart.Text == String.Empty)
            {
                btn_C_Add.Enabled = true;
                btn_edit.Enabled = false;
                btn_delete.Enabled = false;
            }
        }
        int preCartDetailId;

        private void CartsDetailsdataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (CartsDetailsdataGridView.Rows[e.RowIndex].Cells[0].Value != null)
            {
                int id = (int)CartsDetailsdataGridView.Rows[e.RowIndex].Cells[0].Value;
                preCartDetailId = id;
                btnEdit.Enabled = true;
            }
        }

        private void btn_insert_Click(object sender, UpdateFormEventArg e)
        {
            cartDetailViewBindingSource = null;
            if(lstboxCarts.SelectedValue!=null)
            {
                int cartId=(int)lstboxCarts.SelectedValue;
                if(cartId>0)
                {
                    cartDetailViewBindingSource.DataSource = GetCartdetails(cartId);
                    CartsDetailsdataGridView.DataSource = cartDetailViewBindingSource;
                }
            }
        }

        private void btn_Dispose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void CartsEditor_Activated(object sender, EventArgs e)
        {
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void CartsEditor_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void lstboxCarts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstboxCarts.SelectedValue != null)
            {
                int id = (int)lstboxCarts.SelectedValue;
                if (id > 0)
                {
                    Cart cart = ctx.Carts.Single(c => c.Id == id);
                    cartDetailViewBindingSource.DataSource = null;
                    cartDetailViewBindingSource.DataSource = GetCartdetails(cart.Id);
                    CartsDetailsdataGridView.DataSource = cartDetailViewBindingSource;
                    prediCartId = id;
                    txb_AddCart.Text = String.Empty;
                    btn_C_Add.Enabled = true;
                    btn_edit.Enabled = true;
                    btn_delete.Enabled = true;
                }
            }
        }

        private void lstboxCarts_DoubleClick(object sender, EventArgs e)
        {
            if (lstboxCarts.SelectedValue != null)
            {
                int id = (int)lstboxCarts.SelectedValue;
                cartDetailViewBindingSource.DataSource = null;
                List<CartDetailView> cartdetails = GetCartdetails(id);
                cartDetailViewBindingSource.DataSource = cartdetails;
                prediCartId = id;
                txb_AddCart.Text = lstboxCarts.Text;
                btn_C_Add.Enabled = false;
                btn_edit.Enabled = true;
                btn_delete.Enabled = true;

            }
        }

        private void cboSupply_DropDown(object sender, EventArgs e)
        {
            cboSupply.DataSource = ctx.Supplies.ToList();
            cboSupply.DisplayMember = "Name";
            cboSupply.ValueMember = "Id";

        }

        private void txbAmmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !Char.IsNumber(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != '.';
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (lstboxCarts.SelectedValue != null)
            {
                int id = (int)lstboxCarts.SelectedValue;
                if (id > 0)
                {
                    Cart cart = ctx.Carts.Single(c => c.Id == id);
                    if(cboSupply.SelectedValue!=null)
                    {
                        int sid= (int)cboSupply.SelectedValue;
                        CartDetail cdet = new CartDetail();
                        cdet.SupplyId = sid;
                        cdet.Amount = Double.Parse(txbAmmount.Text);
                        cdet.InsertDate = DateTime.Now;
                        cdet.InsertUId = userId;
                        cart.CartDetails.Add(cdet);
                        ctx.SaveChanges();
                        cartDetailViewBindingSource.DataSource=null;
                        cartDetailViewBindingSource.DataSource=GetCartdetails(cart.Id);
                        CartsDetailsdataGridView.DataSource = cartDetailViewBindingSource;
                    }
                }
            }
        }

        private void txbAmmount_TextChanged(object sender, EventArgs e)
        {
            double ammount = 0;
            if (double.TryParse(txbAmmount.Text, out ammount))
            {
                if (ammount > 0)
                {
                    btnAdd.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                }
            }
            else
            {
                btnAdd.Enabled = false;
            }
        }

    }
}
